package com.zjp.blog.controller.manage;

import com.google.gson.Gson;
import com.zjp.blog.controller.BaseController;
import com.zjp.blog.controller.PagerBean;
import com.zjp.blog.data.model.Article;
import com.zjp.blog.data.model.Category;
import com.zjp.blog.data.model.Tag;
import com.zjp.blog.data.model.support.ArticleStates;
import com.zjp.blog.service.ArticleService;
import com.zjp.blog.service.CategoryService;
import com.zjp.blog.service.TagService;
import com.zjp.blog.service.support.ArticleQuery;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.List;

/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */

@Controller
@RequestMapping("/manage/article")
public class ArticleController extends BaseController
{
    private static final Logger logger = LogManager.getLogger(ArticleController.class);

    /*URL*/
    private static String toHome = "/manage/article";

    /*View*/
    public static String WritePost   = "/manage/article/new";
    public static String ArticleHome = "/manage/article/Home";
    public static String articleData = "/manage/article/data";

    @Autowired
    ArticleService articleService;

    @Autowired
    TagService tagService;

    @Autowired
    CategoryService categoryService;

    @RequestMapping(method = RequestMethod.GET)
    public String home(ModelMap map)
    {
        List<Tag> tags = tagService.getAll();
        List<Category> categories = categoryService.getAll();

        map.addAttribute("tags",tags);
        map.addAttribute("categories",categories);

        return ArticleHome;
    }

    @RequestMapping(value = "load" ,method = RequestMethod.GET)
    public String load(@RequestParam(value = "param",defaultValue = "",required = false) String param, PagerBean<Article> page, ModelMap map)
    {
  /*       ExceptionLogger.info(param);*/

         ArticleQuery query = new Gson().fromJson(param,ArticleQuery.class);

         page = articleService.getPage(page,query);

         map.addAttribute("pager",page);
         map.addAttribute("items",page.getRecords());

        return articleData;
    }

    @RequestMapping(value= "write", method = RequestMethod.GET)
    public String write(String id,ModelMap map)
    {
        List<Tag> tags = tagService.getAll();
        List<Category> categories = categoryService.getAll();

        if(!StringUtils.isEmpty(id)) {
            Article article = articleService.getById(Integer.parseInt(id));
            tags.removeAll(article.getTags());

            map.addAttribute("article",article);
        }

        map.addAttribute("categories",categories);
        map.addAttribute("tags",tags);
        map.addAttribute("Status", ArticleStates.values());

        return WritePost;
    }

    @RequestMapping(value = "write", method = RequestMethod.POST)
    public String write(Article article,String tagString,ModelMap map)
    {
        if(hasError(article)) {
            map.addAttribute("item",article);
            return WritePost;
        }

        List<Tag> tags=null;
        Tag temp;
        if(!StringUtils.isEmpty(tagString)) {
            tags = new ArrayList<Tag>();
            for(String s : tagString.split(",")) {
                temp = new Tag();
                temp.setId(Integer.parseInt(s));
                tags.add(temp);
            }
        }

        article.setTags(tags);
        if(article.getId()!=null && article.getId() > 0) {
            articleService.update(article);
        }
        else{
            articleService.create(article);
        }


        return "redirect:" + toHome;
    }

    @RequestMapping("deleteById")
    public String deletePost(String id, RedirectAttributes redirectAttributes)
    {
        if(!StringUtils.isEmpty(id)) {
            Integer post_id = Integer.parseInt(id);
            articleService.delete(post_id);
            addMessage(redirectAttributes,"Delete Success");
        }
        else {
            addError(redirectAttributes,"Delete Failed");
        }

        return "redirect:" + toHome;
    }

    public static String getToHome() {
        return toHome;
    }

    private boolean hasError(Article article)
    {
        if(article == null || StringUtils.isEmpty(article.getTitle()) || StringUtils.isEmpty(article.getContent()) || StringUtils.isEmpty(article.getState()) ) {
            return true;
        }
        return false;
    }

}
